Ext.ns('Wlanauth.user');
Wlanauth.user.ViewDetail = function(ip,type){
	var iWidth=780;                          //弹出窗口的宽度;
    var iHeight=600;                         //弹出窗口的高度;
    //获得窗口的垂直位置
    var iTop = (window.screen.availHeight-30-iHeight)/2;       
    //获得窗口的水平位置
    var iLeft = (window.screen.availWidth-10-iWidth)/2;
    var cfg = 'innerHeight='+iHeight+',width='+iWidth+',innerWidth='+iWidth+',top='+iTop+',left='+iLeft+',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no';
    var url = 'user!viewDetailPage.action?entity.bindIP='+ip;
    if(type=='HISTORY'){
    	url = 'userHis!viewDetailPage.action?entity.bindIP='+ip
    }
	window.open(url,'newwindow'+type,cfg);
}

Wlanauth.user.GridPanel = Ext.extend(Wlanauth.BaseGridPanel,{
	title:'用户管理',
	storeUrl:'user!list.action',
	userStatusType:'',
	constructor:function(cfg){
		Ext.apply(this,cfg);
		
		function getTotalOct(record){
			var inTotal = record.get('sumInputOctets');
			var outTotal = record.get('sumOutputOctets');
			var total =  inTotal+outTotal;
			return  Math.round(total/1024/1024*100)/100;
		}
		function usedOctRender(val,meta,record,row,col,store){
			return Ext.util.Format.number(getTotalOct(record),'0,000.00')
		}
		function leftMoneyRender(val,meta,record,row,col,store){
			var usedOcts = getTotalOct(record);
			var maxMoney = record.get('actualFee');
			var maxOcts = record.get('maxOctets');
			var leftMoney = (maxMoney/maxOcts)*(maxOcts-usedOcts);
			var formatStr = Ext.util.Format.number(leftMoney,'0,000.00');
			if(leftMoney <0.1){
				return '<font style="color:red">'+formatStr+'</font>';
			}
			return formatStr;
		}
		function lastedOctRender(val,meta,record,row,col,store){
			var used = getTotalOct(record);
			var max = record.get('maxOctets')
			var formatStr = Ext.util.Format.number(max-used,'0,000.00');
			if(used/max>0.9){
				return '<font style="color:red">'+formatStr+'</font>';
			}
			return formatStr;
		}
		var userStatusType = this.userStatusType;
		function usernameRender(val,meta,record,row,col,store){
			
			var bindIP = record.get('bindIP');
			var _html= '<a href="javascript:void(0)"' +
				' onclick="Wlanauth.user.ViewDetail(\''+bindIP+'\',\''+userStatusType+'\')" title="查看上网明细">'+val+'</a>';
			
			return _html;
		}
		var expander =new Ext.grid.RowExpander({tpl : 
			new Ext.Template('<ul style="float:left;font-size:12px;color:#666999"><li style="width:150px;float:left">姓名: {displayname}</li><li style="width:250px;float:left">联系电话: {contactPhone}</li><li style="float:left">地址:{address}</li></ul>')}
		);
		this.store = new Ext.data.JsonStore({
			url:this.storeUrl,
			totalProperty:'data',
			root:'rows',
			fields:['id','username','puk','actualFee','displayname','bindIP','email','maxOctets','contactPhone',
			        'sexId','maxFee','address','sumInputOctets','sumOutputOctets','status','batchId',
			        {name:'birth',type:'date',dateFormat:'Y-m-d h:i:s'},
			        {name:'activeTime',type:'date',dateFormat:'Y-m-d H:i:s'},
			        {name:'joinTime',type:'date',dateFormat:'Y-m-d H:i:s'},
			        {name:'expiredTime',type:'date',dateFormat:'Y-m-d H:i:s'},
			        {name:'lastAcctStartTime',type:'date',dateFormat:'Y-m-d H:i:s'},
			        {name:'lastAcctStopTime',type:'date',dateFormat:'Y-m-d H:i:s'}]
			
		});
		var sm = new Ext.grid.CheckboxSelectionModel();
		var config = {
			loadMask:true,
			sm:sm,
			cm:new Ext.grid.ColumnModel({
				columns:[new Ext.grid.RowNumberer(),sm,
				    {header:'批次号',dataIndex:'batchId',width:120},
				    {header:'卡号',dataIndex:'username',width:150,renderer:usernameRender},
					{header:'绑定IP',id:'bindIP',dataIndex:'bindIP',sortable:true},
				    {header:'总流量(MB)',dataIndex:'maxOctets',width:90,sortable:true,renderer:Ext.util.Format.numberRenderer('0,000.00')},
				    {header:'已用流量(MB)',dataIndex:'sumInputOctets',width:90,renderer:usedOctRender,sortable:true},
				    {header:'剩余流量(MB)',dataIndex:'sumInputOctets',width:90,renderer:lastedOctRender,sortable:true},
				    {header:'总金额(元)',dataIndex:'actualFee',width:70,sortable:true,renderer:Ext.util.Format.numberRenderer('0,000.00')},
				    {header:'剩余金额(元)',dataIndex:'actualFee',width:90,renderer:leftMoneyRender,sortable:true},
				    {header:'状态',dataIndex:'status',width:50,renderer:this.statusRender,sortable:true,hidden:userStatusType=='ONLINE'},
				    {header:'最后登陆',dataIndex:'lastAcctStartTime',width:120,renderer:Ext.util.Format.dateRenderer("Y-m-d H:i:s"),sortable:true,hidden:userStatusType!='ONLINE'},
				    {header:'有效期',dataIndex:'expiredTime',width:80,renderer:Ext.util.Format.dateRenderer("Y-m-d"),sortable:true},
				    {header:'激活日期',dataIndex:'activeTime',width:100,renderer:Ext.util.Format.dateRenderer("Y-m-d"),sortable:true}
				   
			    ]}),
			 viewConfig: {
	            forceFit: true
			 },
			 autoExpandColumn:'bindIP'
		};
		
		Wlanauth.user.GridPanel.superclass.constructor.call(this,config);
		//this.fireEvent('autoload');
		this.on('rowdblclick',this.editObject,this);
	},
	
	statusRender:function(val,meta,record,row,col,store){
		if(val == 'DISABLED'){
			return '<font style="color:red">禁 用</font>';
		} else {
			if(record.get('lastAcctStartTime')!=null&&record.get('lastAcctStopTime')==null){
				return '<font style="color:green">在 线</font>';
		 	}
			return '<font style="color:blue">启 用</font>';
		}
	},
	
	editObject:function(){
		var r = this.getSelectionModel().getSelected();
		if(!r){Ext.Msg.alert('提示','请选择一项');return;}
		if(this.userStatusType=='HISTORY'){//历史用户不能修改
			Ext.Msg.alert('提示','不能修改历史用户资料!');
			return ;
		}
		ZZExt.ApplicationContext.openTab('wlanauth.user.editformpanel',{ZZExtParams:{id:r.get('id')}});
	},
	moveToHis:function(){
		var rs = this.getSelectionModel().getSelections();
		if(rs.length<1){Ext.Msg.alert('提示','请至少选择一项');return;}
		this.moveRecordsToHis(rs);
	},
	moveAllToHis:function(){
		var count = this.store.getCount();
		var rs = [];
		for (var i = 0; i < count; i++) {
			 var record = this.store.getAt(i);
			 rs.push(record);
		}
		if(rs.length<1){
			Ext.Msg.alert('提示','无任何记录');
			return;
		}
		this.moveRecordsToHis(rs);
	},
	moveRecordsToHis:function(rs){
		var ids = '',_html='';
		for(var i=0;i<rs.length;i++){
			ids+=rs[i].get('id');
			if(i%5==0){
				_html+='<br/>';
			}
			_html+=rs[i].get('username');
			if(i<rs.length-1){
				ids+=',';
				_html+=' ; ';
			}
		}
		var grid = this;
		Ext.Msg.confirm('<span style="color:red">重要提示</span>','您确认将如下用户信息转为历史用户吗? 卡号:<br/>'+_html,function(btn){
			if(btn=='yes'){
				Ext.Msg.wait('正在转移用户资料...');
				Ext.Ajax.request({
					method:'POST',
					params:{userIds:ids},
					url:'user!moveToHis.action',
					success:function(response,opts){
						if(checkException(response)){
							Ext.Msg.alert('提示','转至历史用户成功');
							grid.getStore().reload();
						} 
					}
				
				});
			}
		});
	},
	toExcel:function(){
		var win = new Wlanauth.user.ExcelConfigWindow({grid:this});
		win.show();
		
	},
	switchStatus:function(){
		var grid = this;
		var rs = this.getSelectionModel().getSelections();
		if(rs.length<1){Ext.Msg.alert('提示','请至少选择一项');return;}
		var ids_disabled = '',ids_enabled='';
		var html_disabled = '',html_enabled = '';
		for(var i=0;i<rs.length;i++){
			if(rs[i].get('status')=='DISABLED'){
				ids_disabled+=','+rs[i].get('id');
				html_disabled+=','+rs[i].get('username');
			} else {
				ids_enabled+=','+rs[i].get('id');
				html_enabled+=','+rs[i].get('username');
			}
		}
		var msg = '';
		if(ids_disabled!=''){
			msg +='<font style="color:blue">启用以下卡号:</font><br/>'+html_disabled.substring(1)+'<br/>';
		} 
		if(ids_enabled!=''){
			msg +='<font style="color:red">禁用以下卡号:</font><br/>'+html_enabled.substring(1);
		}
		var ids = ids_disabled+ids_enabled;
		//不分开了，合并一起切换状态
		if(ids!=''){ ids = ids.substring(1);}
		Ext.Msg.confirm('提示',msg,function(btn){
			if(btn=='yes'){
				Ext.Msg.wait('切换状态...');
				Ext.Ajax.request({
					url:'user!batchSwitchStatus.action',
					params:{userIds:ids},
					success:function(response,opts){
						if(checkException(response)){
							Ext.Msg.alert('提示','状态切换成功');
							grid.getStore().reload();
						}
					}
				
				});
			} 
		});
	},
	deleteObject:function(){
		var grid = this;
		var rs = this.getSelectionModel().getSelections();
		if(rs.length<1){Ext.Msg.alert('提示','请至少选择一项');return;}
		var ids = '',_html='';
		for(var i=0;i<rs.length;i++){
			ids+=rs[i].get('id');
			if(i%5==0){
				_html+='<br/>';
			}
			_html+=rs[i].get('username');
			if(i<rs.length-1){
				ids+=',';
				_html+=' ; ';
			}
		}
		Ext.Msg.confirm('警告','<font style="color:red;font-weight:bold">您确定删除以下记录吗?  卡号:</font><br/>'+_html,function(btn){
			if(btn=='yes'){
				Ext.Msg.wait('删除...');
				Ext.Ajax.request({
					url:'user!batchDelete.action',
					params:{userIds:ids},
					success:function(response,opts){
						if(checkException(response)){
							Ext.Msg.alert('提示','删除成功');
							grid.getStore().reload();
						}
					}
				
				});
			} 
		});
		
	}
	
});

Ext.reg('wlanauth.user.gridpanel',Wlanauth.user.GridPanel);